//
//  StatsInfoViewController.m
//  NemoSDKDemo
//
//  Created by zhaoyun on 2016/10/14.
//  Copyright © 2016年 ainemo. All rights reserved.
//

#import "StatsInfoViewController.h"

#define NA_VALUE @"--"
#define NETWORK_PROBE @"网络探测"
#define CHANNEL_NAME @"通道名称"
#define BAND_WIDTH @"带宽(bps)"
#define LOST_RATE @"丢包率(%)"
#define ROUND_TRIP_TIME @"往返延时(ms)"
#define JITTER @"抖动(ms)"
#define SEND @"发送"
#define RECEIVE @"接收"
#define CONTENT_SHARE @"内容共享"
#define CODEC_TYPE @"codec"
#define RESOLUTION @"分辨率"
#define FRAME_RATE @"帧率(fps)"
#define CODE_RATE @"码率(bps)"
#define VIDEO_SEND @"视频发送"
#define AUDIO_SEND @"音频发送"
#define PARTICIPANTS @"与会者"
#define AUDIO_RECEIVE @"音频接收"
#define VIDEO_RECEIVE @"视频接收"

#import "NSString+Nemo.h"
#import "NSData+Nemo.h"

@interface StatsInfoViewController ()
<UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout>
{
    NSTimer *_timer;
}

@property (nonatomic, strong) NSMutableArray *statsDataArray;

@end

@implementation StatsInfoViewController

- (void)statisticsTimer:(NSTimer *)timer
{
    [_statsDataArray removeAllObjects];
    NSString *statsInfo = [[XYSDKManager sharedInstance] getGeneralStatistics];
    
    NSDictionary *statsDict = [NSJSONSerialization JSONObjectWithData:[statsInfo dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
    if (statsDict)
    {
        //网络探测
        {
            int txBW = 0;
            int txLost = 0;
            int txJitter = 0;
            int rxBW = 0;
            int rxLost = 0;
            int rxJitter = 0;
            int rtt = 0;
            
            NSDictionary *nwDict = [statsDict objectForKey:@"networkInfo"];
            if (nwDict)
            {
                txBW = [[nwDict objectForKey:@"txDetectBw"] intValue];
                txLost = [[nwDict objectForKey:@"txLost"] intValue];
                txJitter = [[nwDict objectForKey:@"txJitter"] intValue];
                
                rxBW = [[nwDict objectForKey:@"rxDetectBw"] intValue];
                rxLost = [[nwDict objectForKey:@"rxLost"] intValue];
                rxJitter = [[nwDict objectForKey:@"rxJitter"] intValue];
                
                rtt = [[nwDict objectForKey:@"rtt"] intValue];
            }
            
            NSMutableArray *nwArray = [[NSMutableArray alloc] init];
            [nwArray removeAllObjects];
            [nwArray addObject:NETWORK_PROBE];
            [nwArray addObject:CHANNEL_NAME];
            [nwArray addObject:BAND_WIDTH];
            [nwArray addObject:LOST_RATE];
            [nwArray addObject:ROUND_TRIP_TIME];
            [nwArray addObject:JITTER];
            [nwArray addObject:SEND];
            [nwArray addObject:[NSString stringWithFormat:@"%d", txBW]];
            [nwArray addObject:[NSString stringWithFormat:@"%d", txLost]];
            [nwArray addObject:[NSString stringWithFormat:@"%d", rtt]];
            [nwArray addObject:[NSString stringWithFormat:@"%d", txJitter]];
            [nwArray addObject:RECEIVE];
            [nwArray addObject:[NSString stringWithFormat:@"%d", rxBW]];
            [nwArray addObject:[NSString stringWithFormat:@"%d", rxLost]];
            [nwArray addObject:[NSString stringWithFormat:@"%d", rtt]];
            [nwArray addObject:[NSString stringWithFormat:@"%d", rxJitter]];
            
            [_statsDataArray addObject:nwArray];
        }
        
        //内容共享
        {
            int arxBw = 0;
            NSString *arxCodec = @"";
            int vrxBw = 0;
            NSString *vrxCodec = @"";
            NSString *vrxRes = @"";
            int vrxFPS = 0;
            
            BOOL hasContent = NO;
            NSDictionary *contentDict = [statsDict objectForKey:@"content"];
            if (contentDict)
            {
                NSArray *arxDict = [contentDict objectForKey:@"audioRxInfo"];
                NSArray *vrxDict = [contentDict objectForKey:@"videoRxInfo"];
                
                hasContent = (arxDict && arxDict.count>0) && (vrxDict && vrxDict.count>0);
                if (hasContent)
                {
                    arxBw = [[[arxDict objectAtIndex:0] objectForKey:@"actBw"] intValue];
                    arxCodec = [[arxDict objectAtIndex:0] objectForKey:@"codecType"];
                    if ([NSString nemo_isEmptyString:arxCodec])
                        arxCodec = @"";
                    
                    vrxBw = [[[vrxDict objectAtIndex:0] objectForKey:@"actBw"] intValue];
                    vrxCodec = [[vrxDict objectAtIndex:0] objectForKey:@"codecType"];
                    if ([NSString nemo_isEmptyString:vrxCodec])
                        vrxCodec = @"";
                    
                    vrxRes = [[vrxDict objectAtIndex:0] objectForKey:@"resolution"];
                    if ([NSString nemo_isEmptyString:vrxRes])
                        vrxRes = @"";
                    
                    vrxFPS = [[[vrxDict objectAtIndex:0] objectForKey:@"frameRate"] intValue];
                }
            }
            
            if (hasContent)
            {
                NSMutableArray *contentArray = [[NSMutableArray alloc] init];
                [contentArray removeAllObjects];
                [contentArray addObject:CONTENT_SHARE];
                [contentArray addObject:CHANNEL_NAME];
                [contentArray addObject:CODEC_TYPE];
                [contentArray addObject:RESOLUTION];
                [contentArray addObject:FRAME_RATE];
                [contentArray addObject:CODE_RATE];
                [contentArray addObject:VIDEO_RECEIVE];
                [contentArray addObject:vrxCodec];
                [contentArray addObject:vrxRes];
                [contentArray addObject:[NSString stringWithFormat:@"%d", vrxFPS]];
                [contentArray addObject:[NSString stringWithFormat:@"%d", vrxBw]];
                [contentArray addObject:AUDIO_RECEIVE];
                [contentArray addObject:arxCodec];
                [contentArray addObject:NA_VALUE];
                [contentArray addObject:NA_VALUE];
                [contentArray addObject:[NSString stringWithFormat:@"%d", arxBw]];
                
                [_statsDataArray addObject:contentArray];
            }
        }
        
        //与会者
        {
            NSMutableArray *peopleArray = [[NSMutableArray alloc] init];
            [peopleArray removeAllObjects];
            [peopleArray addObject:PARTICIPANTS];
            [peopleArray addObject:@""];
            [peopleArray addObject:CHANNEL_NAME];
            [peopleArray addObject:CODEC_TYPE];
            [peopleArray addObject:RESOLUTION];
            [peopleArray addObject:FRAME_RATE];
            [peopleArray addObject:CODE_RATE];
            
            NSDictionary *peopleDict = [statsDict objectForKey:@"people"];
            if (peopleDict)
            {
                //audio TX
                NSString *atxCodec = @"";
                int atxBw = 0;
                NSArray *atxDict = [peopleDict objectForKey:@"audioTxInfo"];
                if (atxDict && atxDict.count>0)
                {
                    atxCodec = [[atxDict objectAtIndex:0] objectForKey:@"codecType"];
                    if ([NSString nemo_isEmptyString:atxCodec])
                        atxCodec = @"";
                    
                    for (NSDictionary *dict in atxDict)
                    {
                        atxBw += [[dict objectForKey:@"actBw"]intValue];
                    }
                }
                [peopleArray addObject:@""];
                [peopleArray addObject:AUDIO_SEND];
                [peopleArray addObject:atxCodec];
                [peopleArray addObject:NA_VALUE];
                [peopleArray addObject:NA_VALUE];
                [peopleArray addObject:[NSString stringWithFormat:@"%d", atxBw]];
                
                //audio RX
                NSString *arxCodec = @"";
                int arxBw = 0;
                NSArray *arxDict = [peopleDict objectForKey:@"audioRxInfo"];
                if (arxDict && arxDict.count>0)
                {
                    arxCodec = [[arxDict objectAtIndex:0] objectForKey:@"codecType"];
                    if ([NSString nemo_isEmptyString:arxCodec])
                        arxCodec = @"";
                    
                    for (NSDictionary *dict in arxDict)
                    {
                        arxBw += [[dict objectForKey:@"actBw"]intValue];
                    }
                }
                [peopleArray addObject:@""];
                [peopleArray addObject:AUDIO_RECEIVE];
                [peopleArray addObject:arxCodec];
                [peopleArray addObject:NA_VALUE];
                [peopleArray addObject:NA_VALUE];
                [peopleArray addObject:[NSString stringWithFormat:@"%d", arxBw]];
                
                //VIDEO TX
                NSArray *vtxDict = [peopleDict objectForKey:@"videoTxInfo"];
                if (vtxDict && vtxDict.count>0)
                {
                    for (NSDictionary *dict in vtxDict)
                    {
                        [peopleArray addObject:[XYSDKManager sharedInstance].user.displayName];
                        [peopleArray addObject:VIDEO_SEND];
                        
                        NSString *vtxCodec = [dict objectForKey:@"codecType"];
                        if ([NSString nemo_isEmptyString:vtxCodec])
                            vtxCodec = @"";
                        [peopleArray addObject:vtxCodec];
                        NSString *vtxRes = [dict objectForKey:@"resolution"];
                        if ([NSString nemo_isEmptyString:vtxRes])
                            vtxRes = @"";
                        
                        [peopleArray addObject:vtxRes];
                        int vtxFPS = [[dict objectForKey:@"frameRate"] intValue];
                        [peopleArray addObject:[NSString stringWithFormat:@"%d", vtxFPS]];
                        int vtxBw = [[dict objectForKey:@"actBw"] intValue];
                        [peopleArray addObject:[NSString stringWithFormat:@"%d", vtxBw]];
                    }
                }
                
                /*
                //audio TX
                NSArray *atxDict = [peopleDict objectForKey:@"audioTxInfo"];
                if (atxDict && atxDict.count>0)
                {
                    for (NSDictionary *dict in atxDict)
                    {
                        [peopleArray addObject:[CloudManager sharedInstance].currentAccount.userProfile.displayName];
                        [peopleArray addObject:AUDIO_SEND];
                        
                        NSString *atxCodec = [dict objectForKey:@"codecType"];
                        if ([NSString isEmptyString:atxCodec])
                            atxCodec = @"";
                        [peopleArray addObject:atxCodec];
                        
                        [peopleArray addObject:NA_VALUE];
                        [peopleArray addObject:NA_VALUE];
                        
                        int atxBw = [[dict objectForKey:@"actBw"] intValue];
                        [peopleArray addObject:[NSString stringWithFormat:@"%d", atxBw]];
                    }
                }
                */
                
                //Video RX
                NSArray *vrxDict = [peopleDict objectForKey:@"videoRxInfo"];
                if (vrxDict && vrxDict.count>0)
                {
                    for (NSDictionary *dict in vrxDict)
                    {
                        NSString *displayName = [dict objectForKey:@"disName"];
                        if ([NSString nemo_isEmptyString:displayName])
                            displayName = @"";
                        
                        displayName = [[NSString alloc] initWithData:[NSData nemo_dataFromBase64String:displayName] encoding:NSUTF8StringEncoding];
                        
                        [peopleArray addObject:displayName];
                        [peopleArray addObject:VIDEO_RECEIVE];
                        
                        NSString *vrxCodec = [dict objectForKey:@"codecType"];
                        if ([NSString nemo_isEmptyString:vrxCodec])
                            vrxCodec = @"";
                        [peopleArray addObject:vrxCodec];
                        
                        NSString *vrxRes = [dict objectForKey:@"resolution"];
                        if ([NSString nemo_isEmptyString:vrxRes])
                            vrxRes = @"";
                        [peopleArray addObject:vrxRes];
                        int vrxFPS = [[dict objectForKey:@"frameRate"] intValue];
                        [peopleArray addObject:[NSString stringWithFormat:@"%d", vrxFPS]];
                        int vrxBw = [[dict objectForKey:@"actBw"] intValue];
                        [peopleArray addObject:[NSString stringWithFormat:@"%d", vrxBw]];
                    }
                }
                
                /*
                //audioRx
                NSArray *arxDict = [peopleDict objectForKey:@"audioRxInfo"];
                if (arxDict && arxDict.count>0)
                {
                    for (NSDictionary *dict in arxDict)
                    {
                        NSString *displayName = [dict objectForKey:@"disName"];
                        if ([NSString isEmptyString:displayName])
                            displayName = @"";
                        
                        [peopleArray addObject:displayName];
                        [peopleArray addObject:AUDIO_RECEIVE];
                        
                        NSString *arxCodec = [dict objectForKey:@"codecType"];
                        if ([NSString isEmptyString:arxCodec])
                            arxCodec = @"";
                        [peopleArray addObject:arxCodec];
                        
                        [peopleArray addObject:NA_VALUE];
                        [peopleArray addObject:NA_VALUE];
                        
                        int atxBw = [[dict objectForKey:@"actBw"] intValue];
                        [peopleArray addObject:[NSString stringWithFormat:@"%d", atxBw]];
                    }
                }
                 */
            }
            
            [_statsDataArray addObject:peopleArray];
        }
        [_collectionView reloadData];
    }
}

-(void)prepareDataDict
{
    self.statsDataArray = [[NSMutableArray alloc] init];
    
    /*
    [_statsDataArray addObject:[NSMutableArray arrayWithObject:NETWORK_PROBE]];
    [_statsDataArray addObject:[NSMutableArray arrayWithObject:CONTENT_SHARE]];
    [_statsDataArray addObject:[NSMutableArray arrayWithObject:PARTICIPANTS]];
     */
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(statisticsTimer:) userInfo:nil repeats:YES];
    
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    [self prepareDataDict];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    if ([_timer isValid])
        [_timer invalidate];
}

-(IBAction)exitStatsInfo:(id)sender
{
    if ([_timer isValid])
        [_timer invalidate];
    [self.view removeFromSuperview];
    
    [self removeFromParentViewController];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return _statsDataArray.count;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSMutableArray *array = _statsDataArray[section];
    return array.count>1?array.count-1:0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"StatsInfoCell" forIndexPath:indexPath];
    
    if(cell)
    {
        NSMutableArray *array = _statsDataArray[indexPath.section];
        NSString *itemStr = [array objectAtIndex:indexPath.item+1];
        UILabel *l = [cell.contentView viewWithTag:101];
        l.text = itemStr;
        
        
        int colunmPerRow = (indexPath.section == _statsDataArray.count-1)?  6 : 5;
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = cell.bounds;
        
        if (indexPath.item == 0)
        {
            UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds
                                                           byRoundingCorners:UIRectCornerTopLeft
                                                                 cornerRadii:CGSizeMake(5, 5)];
            maskLayer.path = maskPath.CGPath;
            
        }
        else if (indexPath.item == colunmPerRow-1)
        {
            UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds
                                                           byRoundingCorners:UIRectCornerTopRight
                                                                 cornerRadii:CGSizeMake(5, 5)];
            maskLayer.path = maskPath.CGPath;
        }
        else if (indexPath.item == array.count-colunmPerRow-1)
        {
            UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds
                                                           byRoundingCorners:UIRectCornerBottomLeft
                                                                 cornerRadii:CGSizeMake(5, 5)];
            maskLayer.path = maskPath.CGPath;
        }
        else if (indexPath.item == array.count-2)
        {
            UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds
                                                           byRoundingCorners:UIRectCornerBottomRight
                                                                 cornerRadii:CGSizeMake(5, 5)];
            maskLayer.path = maskPath.CGPath;
        }
        else
        {
            UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds
                                                           byRoundingCorners:0
                                                                 cornerRadii:CGSizeMake(5, 5)];
            maskLayer.path = maskPath.CGPath;
        }
        cell.layer.mask = maskLayer;
    }
    
    
    // Configure the cell
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath

{
    UICollectionReusableView *reusableview = nil;
    
    if (kind == UICollectionElementKindSectionHeader)
    {
        reusableview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"StatsInfoHeader" forIndexPath:indexPath];
        NSMutableArray *array = _statsDataArray[indexPath.section];
        NSString *title = [array objectAtIndex:0];
        UILabel *l = [reusableview viewWithTag:101];
        l.text = title;
    }
    
    return reusableview;
}

#pragma mark <UICollectionViewDelegate>

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat margin = 30.;
    int colunmPerRow = (indexPath.section == _statsDataArray.count-1)?  6 : 5;
    CGSize size = CGSizeMake(((collectionView.bounds.size.width-margin-(colunmPerRow-1))/colunmPerRow),
                             30);
    return size;
}

@end
